import { fetchPermission1,fetchPermission } from '@/api/api'
import router from '@/router/index'
import {asyncRouterMap,constantRouterMap} from '@/router/config.router'
import { recursionRouter } from '@/utils/recursion-router'
import dynamicRouter from '@/router/dynamic-router'
import store from '@/store/index'

const permission = {
    namespaced: true,
    state: {
        permissionList: null /** 所有路由 */,
        sidebarMenu: [] /** 导航菜单 */,
        currentMenu: '' /** 当前active导航菜单 */,
        control_list: [] /** 完整的权限列表 */,
        avatar: ''/** 头像 */,
        account: ''/** 用户角色 */,
        addRouters:[],
        routers: constantRouterMap,
    },
    getters: {},
    mutations: {
        SET_AVATAR(state, avatar) {
            state.avatar = avatar
        },
        SET_ACCOUNT(state, account) {
            state.account = account
            // console.log(state.account,'account')
        },
        SET_PERMISSION(state, routes) {
            state.permissionList = routes
            // console.log(state.permissionList,'permissionList')
        },
        CLEAR_PERMISSION(state) {
            state.permissionList = null
        },
        SET_MENU(state, menu) {
            state.sidebarMenu = menu
            console.log(state.sidebarMenu,'sidebarMenu')
        },
        CLEAR_MENU(state) {
            state.sidebarMenu = []
        },
        SET_CURRENT_MENU(state, currentMenu) {
            state.currentMenu = currentMenu
            // console.log(state.currentMenu,'currentMenu')
        },
        SET_CONTROL_LIST(state, list) {
            state.control_list = list
            // console.log(state.control_list,'control_list')
        },
        SET_ROUTERS: (state, data) => {
            state.addRouters = data
            state.routers = constantRouterMap.concat(data)
            console.log(state.addRouters,'addRouters')
          }
    },
    actions: {
        async FETCH_PERMISSION({ commit, state }) {
            let permissionList = await fetchPermission({token:store.state.UserToken})
            commit('SET_AVATAR', permissionList.avatar)
            commit('SET_ACCOUNT', permissionList.name)
            let routes = recursionRouter(permissionList.data, dynamicRouter)
            let MainContainer = constantRouterMap.find(v => v.path === '/dashboard')
            let children = MainContainer.children
            commit('SET_CONTROL_LIST', [...children, ...dynamicRouter])
            children.push(...routes)
            commit('SET_MENU', children)
            let initialRoutes = router.options.routes
            router.addRoutes(constantRouterMap)
            commit('SET_PERMISSION', [...initialRoutes, ...constantRouterMap])
        },
        GenerateRoutes({ commit }, data) {
            return new Promise(resolve => {
              const { roles } = data
              let accessedRouters
              accessedRouters = filterAsyncRouter(asyncRouterMap, roles)
              console.log(accessedRouters,'accessedRouters')
              commit('SET_ROUTERS', accessedRouters)
              resolve()
            })
          },
        // 动态添加主界面路由，需要缓存
        UpdateAppRouter({ commit }, routes) {
            return new Promise(resolve => {
                let routelist = routes.constRoutes;
                console.log(routelist,'routelist')
                commit('SET_ROUTERS', routelist)
                resolve()
            })
        }
    }
}

export default permission

/**
 * 过滤账户是否拥有某一个权限，并将菜单从加载列表移除
 *
 * @param permission
 * @param route
 * @returns {boolean}
 */
function hasPermission(permission, route) {
    if (route.meta && route.meta.permission) {
      let flag = -1
      for (let i = 0, len = permission.length; i < len; i++) {
        flag = route.meta.permission.indexOf(permission[i])
        if (flag >= 0) {
          return true
        }
      }
      return false
    }
    return true
  }
  
  /**
   * 单账户多角色时，使用该方法可过滤角色不存在的菜单
   *
   * @param roles
   * @param route
   * @returns {*}
   */
  // eslint-disable-next-line
  function hasRole(roles, route) {
    if (route.meta && route.meta.roles) {
      return route.meta.roles.indexOf(roles.id)
    } else {
      return true
    }
  }
  
  function filterAsyncRouter(routerMap, roles) {
    const accessedRouters = routerMap.filter(route => {
      if (hasPermission(roles.permissionList, route)) {
        if (route.children && route.children.length) {
          route.children = filterAsyncRouter(route.children, roles)
          console.log(route.children,'children')
        }
        return true
      }
      return false
    })
    return accessedRouters
  }
